<?php

class PapiWS_Model_BackgroundRenderer {
	
	// Imagemagick image
	public $im = null; 


	public function __construct( $image )
	{
		$this->im = $image;
	}

	public function render( $bg ) {
		if ( $bg->type == PapiWS_Model_BackgroundVO::BACKGROUND_IMAGE )
			$this->renderBackgroundImage( $bg );
		if ( $bg->type == PapiWS_Model_BackgroundVO::BACKGROUND_FILL )
			$this->renderBackgroundFill( $bg );
	}

	private function renderBackgroundImage( $bg ) {

		$bgFile = tempnam( "/tmp", "bgrend" );
		$stat = copy($bg->imageUrl, $bgFile);
		if ( $stat === false ) {
			echo "Copying from $bf->imageUrl -> $bgFile failed";
			die('Failed copy');
		}
		$bgImage = new Imagick($bgFile);

		// resize
		$bgImage->scaleImage( 
			$this->mmToPx($bg->width),
			$this->mmToPx($bg->height)
		);

		$affine = new PapiWS_Model_AffineTransformation();
		$affine->rotate( $bg->angle );
		$affine->translate(
			$this->mmToPx($bg->x), 
			$this->mmToPx($bg->y)
		);

		$draw = new ImagickDraw();
		$draw->affine( $affine->getCurrentMatrix() );
		$bgImage->setImageOpacity($bg->alpha);
		$draw->composite( Imagick::COMPOSITE_OVER, 0, 0, 0, 0, $bgImage);

		$this->im->drawImage( $draw );

		// cleanup
		unlink( $bgFile );
	}

	private function renderBackgroundFill( $bg ) {

		$rgbColor = sprintf("#%06x", $bg->color);

		// no sé si es lo más lindo.. pero anda. :-)
		$draw = new ImagickDraw();
		$draw->setFillColor( $rgbColor );
		$draw->setFillAlpha( $bg->alpha );
		$draw->rectangle( 0, 0, $this->im->getImageWidth(), $this->im->getImageHeight() );
		$this->im->drawImage( $draw );
	}


	// TODO: Mover esto a otro lado.
    function mmToPx( $length )
    {
        // TODO get from conf. Take into account
        // the fact that output DPI != input DPI !!!!
        $dpi = 200;
        $lengthPx = $length * $dpi / 25.4;
        return (int) round( $lengthPx );
    }
}
